using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using Utils;

public class WeaponItem : MonoBehaviour
{
    public int price = 1;

    public GameObject weaponPrefab;
    private GameObject instantiationObj;

    private Transform pos;
    // private TextMeshPro textMeshPro;

    private void Awake()
    {
        pos = UITool.GetComponent<Transform>("Pos", gameObject);
        UITool.GetComponent<TextMeshPro>("PriceText", gameObject).text = price.ToString();
        GeneratePrefab();
        
        InitEvent();
    }

    private void InitEvent()
    {
        
    }

    private void OnDestroy()
    {
#if UNITY_ANDROID
        

        EasyButton.On_ButtonUp -= OnFuncBtnUp;
#endif
    }

    private void GeneratePrefab()
    {
        instantiationObj = Instantiate(weaponPrefab, pos.position, pos.rotation, transform);
        instantiationObj.GetComponent<Weapon>().isCommodity = true;
        instantiationObj.SetActive(true);
    }

    private void BuyWeapon()
    {
        if (GameController.Instance().archiveCtr.TempLevelData.goldNum < price) return;
        GetComponent<Collider2D>().enabled = false;
        print("You Buy and Use the Consumable -- Success");
        GameController.Instance().archiveCtr.TempLevelData.goldNum -= price;
        GameController.Instance().weaponCtr.Weapon.PutDown();
        instantiationObj.SetActive(false);

        instantiationObj.transform.parent = GameController.Instance().playerCtr.transform;
        Weapon weapon = instantiationObj.GetComponent<Weapon>();
        weapon.equipped = true;
        weapon.canPick = false;
        weapon.GetComponent<Collider2D>().enabled = false;
        GameController.Instance().weaponCtr.Weapon = weapon;
        instantiationObj.SetActive(true);
    }

    private void OnTriggerStay2D(Collider2D other)
    {
        // print(other.name + "[" + other.gameObject.layer + "]--ConsumableTrigger");
        if (Input.GetKey(KeyCode.E) && other.gameObject.layer.Equals(9))
        {
            BuyWeapon();
        }
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
#if UNITY_ANDROID
        if(other.gameObject.layer.Equals(9)) {
            GameController.Instance().panelCtr.phonePanel.SwitchBtnsActive(true);
            EasyButton.On_ButtonUp += OnFuncBtnUp;
        }
        
#endif
    }

    private void OnTriggerExit2D(Collider2D other)
    {
#if UNITY_ANDROID
        if(other.gameObject.layer.Equals(9)) {
            GameController.Instance().panelCtr.phonePanel.SwitchBtnsActive(false);
            EasyButton.On_ButtonUp -= OnFuncBtnUp;
        }
        
#endif
    }

    private void OnFuncBtnUp(string btn_name)
    {
        if (!btn_name.Equals("FuncBtn"))
            return;
        BuyWeapon();
    }
}